//
//  AliyunOSSUpdateTool.swift
//  SwiftProject
//
//  Created by qindong on 2021/7/13.
//

import UIKit

class AliyunOSSUpdateManager: NSObject {
    static var manager = AliyunOSSUpdateManager()

    var ossClient : OSSClient!

    private override init() {
        super.init()

        let credential : OSSCredentialProvider = OSSAuthCredentialProvider(authServerUrl: "http://app.jiyongfq.com/prod-api/app/oss/stsOuah")
        let config = OSSClientConfiguration()
        config.maxRetryCount = 2
        config.timeoutIntervalForRequest = 30
        config.timeoutIntervalForResource = 30
        config.maxConcurrentRequestCount = 10
        ossClient = OSSClient(endpoint: "https://oss-cn-hangzhou.aliyuncs.com", credentialProvider: credential, clientConfiguration: config)
    }
}

extension OSSClient {
    private func updateSingleImage(_ data : Data, _ objectName : String, _ success : @escaping (_ imageUrl : String)->Void, _ failure : @escaping (_ message : String)->Void) {
        let put : OSSPutObjectRequest = OSSPutObjectRequest()
        put.bucketName = "waller"
        put.objectKey = objectName
        put.uploadingData = data
        put.uploadProgress = { bytesSent, totalByteSent, totalBytesExpectedToSend in
            
        }
        let putTask = putObject(put)
        putTask.continue ({ (task: OSSTask<AnyObject>) -> Any? in
            var task = task
            task = self.presignPublicURL(withBucketName: "waller", withObjectKey: objectName)
            if task.error == nil {
                success(task.result as! String)
            } else {
                failure(task.error?.localizedDescription ?? "")
            }
            return nil
        })
    }
    
    func updateImagesWith(imageArray : [Data], inView : UIView, success : @escaping (_ nameArray : [String]) -> Void, failure : @escaping (_ message : String) -> Void) {
        var tempStr : String = ""
        if imageArray.count > 0 {
            tempStr = "图片（0/\(imageArray.count)）"
        } else {
            return
        }
        QMUITips.showLoading("上传中...", detailText: tempStr, in: inView)
        var currentIndex : Int = 0
        var imgArray : [String] = []

        let namePrefix : String = "\(Date().year)" + String(format: "%02d", Date().month) + String(format: "%02d", Date().day)

        for value in imageArray {
            updateSingleImage(value, namePrefix + "/\(String.random(6))\(Int(Date().timeIntervalSince1970)).jpg") { imageUrl in
                imgArray.append(imageUrl)
                currentIndex += 1
                tempStr = "图片（\(currentIndex)/\(imageArray.count)）"
                DispatchQueue.main.async {
                    QMUITips.showLoading("上传中...", detailText: tempStr, in: inView)
                }
                if currentIndex == imageArray.count {
                    DispatchQueue.main.async {
                        success(imgArray)
                        QMUITips.hideAllTips()
                    }
                }
            } _: { _ in
                DispatchQueue.main.async {
                    QMUITips.showError("上传失败，请重试")
                }
            }
        }
    }
}
